<template>
  <div class="tracking-drawer">
    <el-drawer
      :visible.sync="visible"
      :before-close="handleClose"
      title="运单轨迹详情"
      size="60%"
      direction="rtl"
    >
      <div class="drawer-content" v-loading="loading">
        <!-- 运单基本信息 -->
        <div class="shipment-info" v-if="shipmentInfo">
          <el-card shadow="never" class="info-card">
            <div slot="header" class="card-header">
              <span>运单基本信息</span>
            </div>
            <div class="info-content">
              <div class="info-row">
                <div class="info-item">
                  <span class="label">运单号：</span>
                  <span class="value">{{ shipmentInfo.shipmentCode }}</span>
                </div>
                <div class="info-item">
                  <span class="label">运单状态：</span>
                  <el-tag :type="getStatusType(shipmentInfo.status)" size="small">
                    {{ shipmentInfo.statusText }}
                  </el-tag>
                </div>
                <div class="info-item">
                  <span class="label">目的地：</span>
                  <span class="value">
                    {{ shipmentInfo.destinationProvince }}
                    {{ shipmentInfo.destinationCity }}
                    {{ shipmentInfo.destinationDistrict }}
                  </span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label">收货联系人：</span>
                  <span class="value">{{ shipmentInfo.receiverContact }}</span>
                </div>
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ shipmentInfo.receiverPhone }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ parseTime(shipmentInfo.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 轨迹查看和展示模式切换 -->
        <div class="tracking-mode-switch">
          <el-card shadow="never" class="mode-card">
            <div class="mode-content">
              <div class="mode-section">
                <span class="mode-label">轨迹查看模式：</span>
                <el-radio-group v-model="viewMode" @change="handleViewModeChange">
                  <el-radio label="overall">总体轨迹</el-radio>
                  <el-radio label="daily">按天查看</el-radio>
                </el-radio-group>
                
                <!-- 按天查看时的日期选择 -->
                <div v-if="viewMode === 'daily'" class="date-selector">
                  <el-select
                    v-model="selectedDate"
                    placeholder="选择查看日期"
                    @change="handleDateChange"
                    style="width: 150px; margin-left: 20px;"
                  >
                    <el-option
                      v-for="date in availableDates"
                      :key="date"
                      :label="date"
                      :value="date"
                    />
                  </el-select>
                </div>
              </div>
              
              <div class="mode-section">
                <span class="mode-label">轨迹展示：</span>
                <el-radio-group v-model="displayMode" @change="handleDisplayModeChange">
                  <el-radio label="timeline">时间线</el-radio>
                  <el-radio label="map">地图轨迹</el-radio>
                </el-radio-group>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 地图轨迹展示 -->
        <div v-if="displayMode === 'map'" class="tracking-map">
          <el-card shadow="never" class="map-card">
            <div slot="header" class="card-header">
              <span>运单轨迹地图</span>
              <el-button
                type="text"
                icon="el-icon-refresh"
                @click="refreshTracking"
                size="small"
              >
                刷新
              </el-button>
            </div>
            <div class="map-container">
              <div id="tracking-map" class="map-view"></div>
              <div class="map-legend">
                <div class="legend-item">
                  <span class="legend-icon start"></span>
                  <span class="legend-text">起点</span>
                </div>
                <div class="legend-item">
                  <span class="legend-icon transit"></span>
                  <span class="legend-text">中转点</span>
                </div>
                <div class="legend-item">
                  <span class="legend-icon end"></span>
                  <span class="legend-text">终点</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 轨迹时间线 -->
        <div v-if="displayMode === 'timeline'" class="tracking-timeline">
          <el-card shadow="never" class="timeline-card">
            <div slot="header" class="card-header">
              <span>运单轨迹</span>
              <el-button
                type="text"
                icon="el-icon-refresh"
                @click="refreshTracking"
                size="small"
              >
                刷新
              </el-button>
            </div>
            
            <!-- 总体轨迹显示 -->
            <div v-if="viewMode === 'overall'" class="overall-timeline">
              <el-timeline v-if="trackingList.length > 0">
                <el-timeline-item
                  v-for="(item, index) in trackingList"
                  :key="item.id"
                  :timestamp="parseTime(item.timestamp, '{y}-{m}-{d} {h}:{i}')"
                  :type="getTrackingType(item.status)"
                  :icon="getTrackingIcon(item.status)"
                  placement="top"
                >
                  <div class="timeline-content">
                    <div class="timeline-header">
                      <span class="status-text">【{{ item.statusText }}】</span>
                      <span class="location">{{ item.location }}</span>
                    </div>
                    <div class="timeline-body">
                      <p class="remark">{{ item.remark }}</p>
                      <p class="operator" v-if="item.operator">
                        <i class="el-icon-user"></i>
                        操作人：{{ item.operator }}
                      </p>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
              <el-empty v-else description="暂无轨迹信息" />
            </div>
            
            <!-- 按天轨迹显示 -->
            <div v-if="viewMode === 'daily'" class="daily-timeline">
              <div v-if="dailyTracking.length > 0">
                <div
                  v-for="dayData in dailyTracking"
                  :key="dayData.date"
                  class="daily-section"
                >
                  <div class="daily-header">
                    <h4>{{ dayData.date }}</h4>
                    <el-tag size="mini" type="info">{{ dayData.tracks.length }}条记录</el-tag>
                  </div>
                  <el-timeline>
                    <el-timeline-item
                      v-for="item in dayData.tracks"
                      :key="item.id"
                      :timestamp="parseTime(item.timestamp, '{h}:{i}')"
                      :type="getTrackingType(item.status)"
                      :icon="getTrackingIcon(item.status)"
                      placement="top"
                    >
                      <div class="timeline-content">
                        <div class="timeline-header">
                          <span class="status-text">【{{ item.statusText }}】</span>
                          <span class="location">{{ item.location }}</span>
                        </div>
                        <div class="timeline-body">
                          <p class="remark">{{ item.remark }}</p>
                          <p class="operator" v-if="item.operator">
                            <i class="el-icon-user"></i>
                            操作人：{{ item.operator }}
                          </p>
                        </div>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
              <el-empty v-else description="暂无轨迹信息" />
            </div>
          </el-card>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getShipmentTracking } from '../api/comprehensive'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'TrackingDrawer',
  props: {
    // 抽屉显示状态
    visible: {
      type: Boolean,
      default: false
    },
    // 运单信息
    shipmentInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 加载状态
      loading: false,
      // 查看模式
      viewMode: 'overall',
      // 展示模式
      displayMode: 'timeline',
      // 轨迹列表
      trackingList: [],
      // 按天分组的轨迹
      dailyTracking: [],
      // 选中的日期
      selectedDate: '',
      // 可用日期列表
      availableDates: [],
      // 地图实例
      map: null,
      // 地图标记点
      markers: []
    }
  },
  watch: {
    visible(val) {
      if (val && this.shipmentInfo) {
        this.loadTrackingData()
      }
    },
    shipmentInfo(val) {
      if (val && this.visible) {
        this.loadTrackingData()
      }
    }
  },
  methods: {
    // 解析时间
    parseTime,
    
    /** 加载轨迹数据 */
    async loadTrackingData() {
      if (!this.shipmentInfo || !this.shipmentInfo.id) return
      
      this.loading = true
      try {
        const params = {
          viewMode: this.viewMode,
          date: this.selectedDate
        }
        
        const response = await getShipmentTracking(this.shipmentInfo.id, params)
        
        if (response.code === 200) {
          if (this.viewMode === 'overall') {
            this.trackingList = response.data.trackingList || []
            // 提取可用日期
            this.extractAvailableDates()
          } else {
            this.dailyTracking = response.data.dailyTracking || []
          }
        }
      } catch (error) {
        console.error('加载轨迹数据失败:', error)
        this.$message.error('加载轨迹数据失败')
      } finally {
        this.loading = false
      }
    },
    
    /** 提取可用日期 */
    extractAvailableDates() {
      const dates = new Set()
      this.trackingList.forEach(item => {
        const date = item.timestamp.split(' ')[0]
        dates.add(date)
      })
      this.availableDates = Array.from(dates).sort((a, b) => new Date(b) - new Date(a))
      if (this.availableDates.length > 0 && !this.selectedDate) {
        this.selectedDate = this.availableDates[0]
      }
    },
    
    /** 查看模式切换 */
    handleViewModeChange(mode) {
      this.viewMode = mode
      this.loadTrackingData()
    },
    
    /** 日期选择变化 */
    handleDateChange(date) {
      this.selectedDate = date
      this.loadTrackingData()
    },
    
    /** 刷新轨迹数据 */
    refreshTracking() {
      this.loadTrackingData()
    },
    
    /** 关闭抽屉 */
    handleClose() {
      this.$emit('close')
    },
    
    /** 获取运单状态类型 */
    getStatusType(status) {
      const statusMap = {
        '0': 'info',     // 待发货
        '1': 'warning',  // 运输中
        '2': 'primary',  // 派送中
        '3': 'success',  // 已签收
        '4': 'danger'    // 异常
      }
      return statusMap[status] || 'info'
    },
    
    /** 获取轨迹类型 */
    getTrackingType(status) {
      const typeMap = {
        'shipped': 'primary',
        'transit': 'warning',
        'delivering': 'info',
        'delivered': 'success',
        'exception': 'danger'
      }
      return typeMap[status] || 'info'
    },
    
    /** 获取轨迹图标 */
    getTrackingIcon(status) {
      const iconMap = {
        'shipped': 'el-icon-truck',
        'transit': 'el-icon-position',
        'delivering': 'el-icon-bicycle',
        'delivered': 'el-icon-check',
        'exception': 'el-icon-warning'
      }
      return iconMap[status] || 'el-icon-info'
    },
    
    /** 展示模式切换 */
    handleDisplayModeChange(mode) {
      this.displayMode = mode
      if (mode === 'map') {
        this.$nextTick(() => {
          this.initMap()
        })
      }
    },
    
    /** 初始化地图 */
    initMap() {
      // 模拟地图初始化（实际项目中需要引入高德地图或百度地图SDK）
      const mapContainer = document.getElementById('tracking-map')
      if (!mapContainer) return
      
      // 清除之前的地图
      if (this.map) {
        this.clearMap()
      }
      
      // 创建模拟地图
      this.createMockMap()
    },
    
    /** 创建模拟地图 */
    createMockMap() {
      const mapContainer = document.getElementById('tracking-map')
      if (!mapContainer) return
      
      // 清空容器
      mapContainer.innerHTML = ''
      
      // 创建地图画布
      const canvas = document.createElement('canvas')
      canvas.width = mapContainer.clientWidth
      canvas.height = mapContainer.clientHeight
      canvas.style.width = '100%'
      canvas.style.height = '100%'
      canvas.style.background = '#f0f2f5'
      mapContainer.appendChild(canvas)
      
      const ctx = canvas.getContext('2d')
      
      // 绘制模拟轨迹路线
      this.drawTrackingRoute(ctx, canvas.width, canvas.height)
    },
    
    /** 绘制轨迹路线 */
    drawTrackingRoute(ctx, width, height) {
      if (!this.trackingList.length) return
      
      // 模拟轨迹点坐标
      const points = [
        { x: width * 0.1, y: height * 0.8, type: 'start', label: '起点' },
        { x: width * 0.3, y: height * 0.6, type: 'transit', label: '中转1' },
        { x: width * 0.5, y: height * 0.4, type: 'transit', label: '中转2' },
        { x: width * 0.7, y: height * 0.3, type: 'transit', label: '中转3' },
        { x: width * 0.9, y: height * 0.2, type: 'end', label: '终点' }
      ]
      
      // 绘制路线
      ctx.strokeStyle = '#409eff'
      ctx.lineWidth = 3
      ctx.beginPath()
      points.forEach((point, index) => {
        if (index === 0) {
          ctx.moveTo(point.x, point.y)
        } else {
          ctx.lineTo(point.x, point.y)
        }
      })
      ctx.stroke()
      
      // 绘制轨迹点
      points.forEach((point, index) => {
        this.drawTrackingPoint(ctx, point, index)
      })
    },
    
    /** 绘制轨迹点 */
    drawTrackingPoint(ctx, point, index) {
      const colors = {
        start: '#67c23a',
        transit: '#409eff',
        end: '#f56c6c'
      }
      
      // 绘制圆点
      ctx.fillStyle = colors[point.type] || '#909399'
      ctx.beginPath()
      ctx.arc(point.x, point.y, 8, 0, 2 * Math.PI)
      ctx.fill()
      
      // 绘制白色边框
      ctx.strokeStyle = '#fff'
      ctx.lineWidth = 2
      ctx.stroke()
      
      // 绘制标签
      ctx.fillStyle = '#303133'
      ctx.font = '12px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(point.label, point.x, point.y - 15)
      
      // 绘制时间信息
      if (this.trackingList[index]) {
        const timeText = this.parseTime(this.trackingList[index].timestamp, '{m}-{d} {h}:{i}')
        ctx.fillStyle = '#909399'
        ctx.font = '10px Arial'
        ctx.fillText(timeText, point.x, point.y + 25)
      }
    },
    
    /** 清除地图 */
    clearMap() {
      const mapContainer = document.getElementById('tracking-map')
      if (mapContainer) {
        mapContainer.innerHTML = ''
      }
      this.map = null
      this.markers = []
    }
  }
}
</script>

<style lang="scss" scoped>
.tracking-drawer {
  ::v-deep .el-drawer {
    .el-drawer__header {
      padding: 20px 20px 10px;
      margin-bottom: 0;
      border-bottom: 1px solid #ebeef5;
      
      span {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
      }
    }
    
    .el-drawer__body {
      padding: 0;
    }
  }
}

.drawer-content {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  
  .shipment-info {
    margin-bottom: 20px;
    
    .info-card {
      .card-header {
        font-weight: 500;
        color: #303133;
      }
      
      .info-content {
        .info-row {
          display: flex;
          margin-bottom: 15px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .info-item {
            flex: 1;
            display: flex;
            align-items: center;
            
            .label {
              color: #606266;
              margin-right: 8px;
              white-space: nowrap;
            }
            
            .value {
              color: #303133;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
  
  .tracking-mode-switch {
    margin-bottom: 20px;
    
    .mode-card {
      .mode-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 20px;
        
        .mode-section {
          display: flex;
          align-items: center;
          
          .mode-label {
            color: #606266;
            margin-right: 15px;
            white-space: nowrap;
          }
          
          .date-selector {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
  
  .tracking-map {
    margin-bottom: 20px;
    
    .map-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        color: #303133;
      }
      
      .map-container {
        position: relative;
        
        .map-view {
          width: 100%;
          height: 400px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          background: #f0f2f5;
        }
        
        .map-legend {
          position: absolute;
          top: 10px;
          right: 10px;
          background: rgba(255, 255, 255, 0.9);
          padding: 10px;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          
          .legend-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .legend-icon {
              width: 12px;
              height: 12px;
              border-radius: 50%;
              margin-right: 8px;
              
              &.start {
                background: #67c23a;
              }
              
              &.transit {
                background: #409eff;
              }
              
              &.end {
                background: #f56c6c;
              }
            }
            
            .legend-text {
              font-size: 12px;
              color: #303133;
            }
          }
        }
      }
    }
  }
  
  .tracking-timeline {
    .timeline-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        color: #303133;
      }
      
      .overall-timeline,
      .daily-timeline {
        .timeline-content {
          .timeline-header {
            margin-bottom: 8px;
            
            .status-text {
              font-weight: 500;
              color: #409eff;
              margin-right: 10px;
            }
            
            .location {
              color: #303133;
              font-weight: 500;
            }
          }
          
          .timeline-body {
            .remark {
              color: #606266;
              margin: 5px 0;
              line-height: 1.5;
            }
            
            .operator {
              color: #909399;
              font-size: 12px;
              margin: 5px 0 0;
              
              i {
                margin-right: 4px;
              }
            }
          }
        }
      }
      
      .daily-timeline {
        .daily-section {
          margin-bottom: 30px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .daily-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ebeef5;
            
            h4 {
              margin: 0;
              color: #303133;
              font-size: 16px;
              margin-right: 10px;
            }
          }
        }
      }
    }
  }
}

::v-deep .el-timeline {
  .el-timeline-item__timestamp {
    color: #909399;
    font-size: 12px;
  }
  
  .el-timeline-item__wrapper {
    padding-left: 35px;
  }
  
  .el-timeline-item__tail {
    border-left: 2px solid #e4e7ed;
  }
  
  .el-timeline-item__node {
    width: 14px;
    height: 14px;
  }
}
</style>